<template>
  <div class="rightBodyContent" ref="applyHeight">
    <div class="rightBodyContent-in">
      <div class="apply-box">
        <div class="apply-box-left">
          <tips optionTemplate="purchaseApply"></tips>
          <div class="mb-20">
            <div class="mb-10">
              审核流程:
              <el-select placeholder="请选择审核流程" size="small" v-model="flow_id" @change="changeApplyModule()">
                <el-option
                    :label="item.title"
                    :value="item.id"
                    v-for="item in applyModule"
                    :ksy="item.id">
                </el-option>
              </el-select>
            </div>
            <div v-if="flow_id">
              {{ settingName || '--' }}:
              <el-select placeholder="请选择审核人" size="small" v-model="settingExamin" multiple>
                <el-option
                    :label="item.realname"
                    :value="item.id"
                    v-for="item in selectList"
                    :ksy="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <el-button-group style="margin-bottom: 10px;">
            <el-button :type="tabPosition=='materiel'?'primary':''" @click="groupTab('materiel')" size="small">物料申购
            </el-button>
            <el-button :type="tabPosition=='teach'?'primary':''" @click="groupTab('teach')" size="small">教具申购
            </el-button>
            <el-button type="" @click="actionSheet('excel')" size="small">表格导入</el-button>
          </el-button-group>
          <div class="apply-box-left-from">
            <el-form ref="infoForm" :model="infoForm" label-width="100px">
              <el-form-item :label="tabPosition=='materiel'?'物料名称:':'教具名称:'" prop="name">
                <el-autocomplete
                    class="inline-input"
                    v-model="infoForm.name"
                    size="small"
                    value-key="name"
                    :fetch-suggestions="querySearch"
                    :placeholder="tabPosition=='materiel'?'物料名称':'教具名称'"
                    :trigger-on-focus="false"
                    @select="handleSelect"
                ></el-autocomplete>
              </el-form-item>
              <el-form-item label="分类:" v-if="tabPosition=='teach'">
                <el-select placeholder="分类" v-model="infoForm.cate_id" size="small" class="w-140" @change="getChange">
                  <el-option :label="item.name" :value="item.id" v-for="(item, index) in cateList"
                             :key="index"></el-option>
                </el-select>
                <el-select placeholder="分类" v-model="infoForm.cate_son_id" size="small" class="w-140"
                           v-if="cateList[infoForm.cate_id] && cateList[infoForm.cate_id].son">
                  <el-option :label="item.name" :value="item.id" v-for="(item, index) in cateList[infoForm.cate_id].son"
                             :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="申购事由:" prop="reason">
                <el-input v-model="infoForm.reason" placeholder="填写申购事由" size="small"></el-input>
              </el-form-item>
              <el-form-item label="申购数量:" prop="need_number">
                <el-input v-model="infoForm.need_number" placeholder="数量" size="small"></el-input>
              </el-form-item>
              <el-form-item label="单价:" prop="price">
                <el-input v-model="infoForm.price" placeholder="单价" size="small"></el-input>
              </el-form-item>
              <el-form-item label="单位:" prop="need_number" v-if="tabPosition=='materiel'">
                <el-input v-model="infoForm.unit" placeholder="单位" size="small"></el-input>
              </el-form-item>
              <el-form-item :label="tabPosition=='materiel'?'物料照片':'教具照片'" prop="pic">
                <el-button size="small" type="primary" @click="actionSheet('add')">点击上传</el-button>
                <div class="add-img">
                  <div class="rightapply-box-right-list-box-img-in"
                       :style="{backgroundImage:'url('+infoForm.pic+')',backgroundSize:'cover',backgroundPosition:'center'}">
                    <i class="el-icon-camera-solid" v-if="!infoForm.pic"></i>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="链接/单位:" prop="name">
                <el-input v-model="infoForm.url" placeholder="链接/单位" size="small"></el-input>
              </el-form-item>·
              <el-form-item label="期望交付时间:" prop="expect_time">
                <el-date-picker type="date"
                                size="small"
                                placeholder="选择日期"
                                v-model="infoForm.expect_time"
                                :picker-options="pickerOptions1"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
              <el-form-item label="补充说明:" prop="remark">
                <el-input v-model="infoForm.remark" placeholder="补充说明" size="small"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addGoods">添加申购</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="apply-box-right" :style="{height: heightBox+'px'}">
          <div class="apply-box-right-top" v-if="purchase.length">
            <div class="apply-box-right-list" v-for="(item,index) in purchase" :key="index">
              <div class="apply-box-right-list-top">
                <div>
                  <span @click="editGoods('expect_time', index)">{{ index + 1 }}·期望交付日期：{{
                      item.expect_time ? item.expect_time : '--'
                    }}</span>
                </div>
                <div>
                  <span @click="editGoods('url', index)">采购网址：{{ item.url ? item.url : '--' }}</span>
                </div>
              </div>
              <div class="apply-box-right-list-box">
                <div class="rightapply-box-right-list-box-img">
                  <div class="rightapply-box-right-list-box-img-in" @click="actionSheet('list', index)"
                       :style="{backgroundImage:'url('+item.pic+')',backgroundSize:'cover',backgroundPosition:'center'}">
                    <i class="el-icon-camera-solid" v-if="!item.pic"></i>
                  </div>
                  <div class="rightapply-box-right-list-box-img-title">
                    <p>{{ item.name }}</p>
                    <p @click="editGoods('reason', index)">{{ item.reason }}</p>
                  </div>
                </div>
                <div class="rightapply-box-right-list-box-number">
                  <span class="el-icon-remove-outline" @click="addSub(1,index)"></span>
                  <el-input @input="countPrice()" v-model="item.need_number" placeholder="数量" size="small"></el-input>
                  <span class="el-icon-circle-plus-outline" @click="addSub(2,index)"></span>
                </div>
                <div class="rightapply-box-right-list-box-price" @click="editGoods('price', index)">
                  {{ item.price ? item.price : '--' }} <span>元</span>
                </div>
                <div class="detele-box el-icon-error" @click="deleteFn(index)"></div>
              </div>
            </div>
          </div>
          <div class="apply-box-right-top" v-else>
            <div class="upload-demo-line">
              <el-upload
                  class="upload-demo"
                  drag
                  :action="$uploadImg"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  accept=".xls,.xlsx"
                  :show-file-list="false"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传表格文件</div>
              </el-upload>
            </div>
            <div class="apply-nonedata">暂无申购数据</div>
          </div>
          <div class="apply-box-right-bottom">
            <div class="apply-box-right-bottom-l">
              <span>{{ goods_number }}件 总计</span><span class="price">{{ count }}</span><span>元</span>
            </div>
            <div class="apply-box-right-bottom-b">
              <el-button plain size="mini" @click="downexcel" :disabled="purchase.length?false:true">导出当前清单</el-button>
              <el-button type="primary" plain size="mini" @click="onSubmit">确认并提交申购</el-button>
              <el-button type="danger" plain size="mini" @click="clearList">一键清空</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <form style="display: none" enctype="multipart/form-data">
      <input type="file" accept="image/*" @change="handleFile('pic')" class="hiddenInput" id="uploadFile"
             ref="uploadFile"/>
    </form>
    <form style="display: none" enctype="multipart/form-data">
      <input type="file" accept=".xls, .xlsx" @change="handleFile('excel')" class="hiddenExcelInput"
             id="uploadExcelFile" ref="uploadExcelFile"/>
    </form>
    <edit_Item :visible.sync="itemVisible" :itemlable="itemOption"
               :itemValue="purchase.length?purchase[itemIndex][itemOption]:''" @checkList="checkList"></edit_Item>
    <AuxiliaryModule @getInformation="getInformation" :typeData="typeData"></AuxiliaryModule>
    <div style="height: 0px;overflow: hidden;">
      <iframe :src="downExcelSrc" frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
import logopng from '@/assets/imageAdmin/logo.jpg'
import edit_Item from "./edit_Item";
import {purchaseIndex, purchaseDetail, purchaseExport} from '@/api/admin/purchase'

var XLSX = require('xlsx')

export default {
  name: "apply",
  components: {
    edit_Item
  },
  data() {
    return {
      allowed: [
        'xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xls', "application/vnd.ms-excel",
        'csv', "text/csv"],
      typeData: 'purchase_apply',
      logopng: logopng,
      tabPosition: 'materiel',
      infoForm: {
        name: '',
        cate_id: '',
        reason: '',
        unit: '', // "单位",
        need_number: 1,
        price: '',
        pic: '',
        url: '',
        expect_time: '',
        remark: '',
        cate_son_id: ''
      },
      // 限制时间选择
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      heightBox: 0,
      purchase: [],
      cateList: {},
      imgType: '',
      count: 0,
      goods_number: 0,
      itemOption: '',
      itemVisible: false,
      itemIndex: 0,
      picIndex: 0,
      excelFile: '',
      selectList: [],
      settingName: '',
      settingExamin: [],
      applyModule: [],
      flow_id: '',
      downExcelSrc: ''
    }
  },
  created() {
    this.getTeachCate()
    this.countPrice() // 计算总金额
    this.getApplyModule()
  },
  mounted() {
    let n = this;
    this.$nextTick(() => {
      // let height = n.$refs.dialogBox.offsetHeight;  //top 50 1 search 50 page 50 10 footer 50 1
      // this.tableHeight = height - (51 + 50 + 60 + 51)
      console.log('document.body.clientHeight:', document.body.clientHeight)
      console.log('document.body.clientHeight:', document.body.clientHeight - (60 + 50 + 60))
      n.heightBox = document.body.clientHeight - (60 + 50 + 60 + 30)
    })
  },
  methods: {
    // 获取流程模版
    getApplyModule() {
      purchaseIndex({p: 1}).then(res => {
        this.applyModule = res.list.data
        console.log(res)
      })
    },
    // 流程模版变了
    changeApplyModule() {
      this.settingName = '';
      this.selectList = [];
      for (let item of this.applyModule) {
        if (item.id === this.flow_id) {
          this.getModuleInfo(item.id)
        }
      }
    },
    // 获取模版详情信息
    getModuleInfo(id) {
      purchaseDetail({id: id}).then(res => {
        let {vo} = res
        if (vo.flows.length) {
          this.settingName = vo.flows[0].name;
          this.selectList = this.getJson(vo.flows[0].users);
        }
      })
    },
    addGoods() {
      console.log('this.infoForm,', this.infoForm)
      let option = this.getJson(this.infoForm)
      if (!option.name) {
        this.$message.error(this.tabPosition === 'materiel' ? '填写物料名称' : '填写教具名称')
        return
      }
      if (this.tabPosition === 'teach') {
        if (!option.cate_id) {
          this.$message.error('选择教具分类')
          return
        }
      }
      if (!option.need_number) {
        this.$message.error('填写申购数量')
        return
      }
      if (this.tabPosition === 'materiel' && !option.unit) {
        this.$message.error('填写单位')
        return
      }
      option.type = this.tabPosition === 'materiel' ? 0 : 1; // 采购类型0物料1教具
      this.purchase.push(this.getJson(option));
      this.infoForm = {
        name: '',
        cate_id: '',
        reason: '',
        unit: '', // "单位",
        need_number: 1,
        price: '',
        pic: '',
        url: '',
        expect_time: '',
        remark: '',
        cate_son_id: ''
      }
      this.countPrice()
    },
    async onSubmit() {
      console.log('提交的数据：', this.purchase)
      if (!this.flow_id) {
        this.$message.error('请选择审核流程')
        return
      }
      if (!this.purchase.length) {
        this.$message.error('请添加需要申购的物品')
        return
      }
      let optionData = this.getJson(this.purchase);
      let name_ = [];
      let word_price = []
      let word_number = []
      for (let index in optionData) {
        if (optionData[index].cate_son_id) {
          optionData[index].cate_id = optionData[index].cate_son_id;
        }
        delete optionData[index].cate_son_id
        // if(!item.pic){
        //   this.$message.error('请上传申购物件图')
        //   return
        // }
        if (name_.indexOf(optionData[index].name) !== -1) {
          this.$message.error('申购的物件名称不可重复')
          return
        } else {
          name_.push(optionData[index].name)
        }

        // 价格 数量格式 判断
        let price_ = Number(optionData[index].price)
        let nees_number = Number(optionData[index].need_number)
        if (isNaN(price_)) {
          console.log('price_:', price_)
          word_price.push(`【${Number(index) + 1}·${optionData[index].name}】`)
        }
        if (isNaN(nees_number)) {
          console.log('nees_number:', nees_number)
          word_number.push(`【${Number(index) + 1}·${optionData[index].name}】`)
        }
      }
      let string_ = ''
      if (word_price.length) {
        string_ = string_ + word_price.join('') + '，价格格式错误！'
      }
      if (word_number.length) {
        string_ = string_ + word_number.join('') + '，数量格式错误！'
      }
      if (string_) {
        this.$confirm(string_, '错误提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
        }).catch(() => {
        });
        return
      }
      let type = this.tabPosition === 'materiel' ? 1 : 2; // 1 物料 2 教具
      let data = await this.$post(this.api.purchase.add, {
        flow_id: this.flow_id,
        type: type,
        list: JSON.stringify(optionData),
        now_examine: this.settingExamin.join(',')
      });
      console.log('data:', data)
      if (!data.code) {
        this.clearList()
        this.$message.success('申购提交成功！')
      } else {
        this.$message.success(data.msg)
      }
    },
    // 编辑可编辑项
    editGoods(type, index) {
      this.itemOption = type;
      this.itemIndex = index;
      this.itemVisible = true;
    },
    actionSheet(option, index) {
      // option add 添加 list 列表编辑
      // if (option === 'qr_code' && this.familyImg.length >= 4) {
      //   Toast('图片最大限制')
      //   return
      // }
      // console.log('图片最大限制')
      this.imgType = option;
      this.picIndex = index;
      if (option !== 'excel') {
        this.$el.querySelector('.hiddenInput').click()
      } else {
        this.$el.querySelector('.hiddenExcelInput').click()
      }

      // 来回切换 type 使得能够上传同一张图
      // setTimeout(()=>{
      //   this.$el.querySelector('.hiddenInput').setAttribute('type','text')
      // },200)
    },
    async handleFile(option) {
      // 此处不能使用event.target，否则手机上不能显示
      let n = this;
      let file = document.querySelector('#uploadFile')
      if (option === 'excel') {
        file = document.querySelector('#uploadExcelFile')
      }
      let formData = new FormData()
      if (file.files[0]) {
        // Indicator.open('上传中…')
        formData.append('file', file.files[0])
        // 接下来就可以用 ajax 提交 formData
        // this.handleBeforeUpload(file.files[0])
        let data = await this.$post('upload/oldupload', formData);
        console.log('data:', data)
        if (!data.code) {
          // this.imgUpload[this.imgType] = data.pic
          // console.log('this.imgUpload:', this.imgUpload)
          if (this.imgType !== 'excel') {
            if (this.imgType === 'add') {
              n.infoForm.pic = data.data.name
            } else {
              let list = n.getJson(n.purchase[n.picIndex])
              list.pic = data.data.name;
              n.$set(n.purchase, n.picIndex, list)
              // this.imgType = option;
              // this.picIndex = index;
            }
            n.$refs.uploadFile.value = ''
          } else {
            n.excelFile = data.data.name
            n.getExcelDetail()// 获取excel中的数据
            n.$refs.uploadExcelFile.value = ''
          }
          // 来回切换 type text file 以便能够上传选择同一张图
          // setTimeout(() => {
          //   // Indicator.close()
          //   n.$el.querySelector('.hiddenInput').setAttribute('type','file')
          // }, 300)
        }
      }
    },
    async getTeachCate() {
      let data = await this.$post(this.api.tools_category_index, {p: 1});
      if (!data.code) {
        let list_ = data.list
        let obj_ = {}
        let obj_son = {}
        for (let i in list_) {
          if (list_[i].tid === 0) {
            obj_[list_[i].id] = list_[i]
          } else {
            if (obj_son[list_[i].tid]) {
              obj_son[list_[i].tid].push(list_[i])
            } else {
              obj_son[list_[i].tid] = [list_[i]]
            }
          }
        }
        this.coteryList = obj_
        let arrayList = []
        for (let i in obj_) {
          console.log(i)
          if (Number(i) !== 0) {
            if (obj_son[obj_[i].id]) {
              obj_[i].son = obj_son[obj_[i].id]
            }
            arrayList.push(obj_[i])
          }
        }
        this.cateList = this.getJson(obj_)
        // this.editFormVisible = false
      } else {
        console.log('请求失败')
      }
    },
    handleAvatarSuccess(res) {
      console.log('res:', res)
      this.excelFile = res.data.name
      this.getExcelDetail()// 获取excel中的数据
    },
    async getExcelDetail() {
      let data = await this.$post(this.api.purchase.ExcelDetail, {file: this.excelFile});
      console.log('读取excel文件内容：', data)
      // need_number
      if (!data.code) {
        this.purchase = []
        let word_price = []
        let word_number = []
        for (let index in data.list) {
          data.list[index].cate_son_id = '';
          let price_ = Number(data.list[index].price)
          let nees_number = Number(data.list[index].need_number)
          if (isNaN(price_)) {
            console.log('price_:', price_)
            word_price.push(`【${Number(index) + 1}·${data.list[index].name}】`)
          }
          if (isNaN(nees_number)) {
            console.log('nees_number:', nees_number)
            word_number.push(`【${Number(index) + 1}·${data.list[index].name}】`)
          }
          // if (typeof(data.list[index].price) !== 'number') {
          //   console.log('data.list[index].price:', Number.parseFloat(data.list[index].price))
          //   word_.push(`【${Number(index) + 1}·${data.list[index].name}】`)
          // }
          // if(!Number.isNaN(data.list[index].need_number)){
          //   console.log('data.list[index].need_number:', Number.isNaN(data.list[index].need_number))
          // }
          this.purchase.push(this.getJson(data.list[index]));
        }
        if (string_) {
          this.$confirm(string_, '错误提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).then(() => {
          }).catch(() => {
          });
        }
        //  cate_son_id: '' 此处需要进行ID的判断
        this.countPrice()
      }

    },
    getChange() {
      this.cate_son_id = '';
    },
    groupTab(option) {
      if (option !== 'excel') {
        this.tabPosition = option
      }
    },
    checkList(option) {
      // purchase itemIndex
      // {name: this.itemlable,val: this.itemValue}
      console.log('得到的数据：', option)
      let list = this.getJson(this.purchase[this.itemIndex])
      list[option.name] = option.val
      this.$set(this.purchase, this.itemIndex, list)
      if (option.name === 'price') {
        this.countPrice()
      }
    },
    // 计算总金额
    countPrice() {
      let count = 0;
      let number = 0;
      for (let item of this.purchase) {
        count = count + parseFloat(item.price) * Number(item.need_number);
        number = number + Number(item.need_number)
      }
      this.goods_number = number;
      this.count = count.toFixed(2);
    },
    // 获取物料
    async getmMterial(cb, name) {
      let data = await this.$fetch(this.api.admin_materiel_index, {p: 1, name: name});
      if (!data.code) {
        for (let item of data.list.data) {
          item.testname = item.name
          item.name = item.name + '/' + item.unit
        }
        // this.arryList = data.list.data;
        cb(data.list.data);
      }
    },
    // 获取教具
    async getTeaching(cb, name) {
      let data = await this.$fetch(this.api.tools_index, {p: 1, name: name});
      if (!data.code) {
        // this.arryList = data.list.data;
        cb(data.list.data);
      }
    },
    querySearch(queryString, cb) {
      console.log('请求服务起：', queryString)
      let that = this;
      // let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        // cb(results);
        if (that.tabPosition === 'materiel') {
          that.getmMterial(cb, queryString)
        } else {
          that.getTeaching(cb, queryString)
        }
      }, 3000 * Math.random());
    },
    // 是选中某一列触发的事件,在这里item为选中字段所在的对象
    handleSelect(option) {
      console.log('选中的某项', option);
      if (this.tabPosition === 'materiel') {
        this.infoForm.name = option.testname;
        this.infoForm.unit = option.unit;
      } else {
        // 判断分类
        if (option.cate_id) {
          if (this.cateList[option.cate_id]) {
            this.infoForm.cate_id = option.cate_id
          } else {
            for (let item in this.cateList) {
              if (this.cateList[item].son) {
                for (let m of this.cateList[item].son) {
                  if (m.id === option.cate_id) {
                    this.infoForm.cate_id = Number(item);
                    this.infoForm.cate_son_id = m.id;
                  }
                }
              }
            }
          }
        }
      }
    },
    addSub(type, index) {
      // type 1 减 2 加
      let option = this.getJson(this.purchase[index])
      if (type === 1) {
        if (option.need_number === 1) {
          return
        }
        if (Number(option.need_number) > 1) {
          option.need_number = Number(option.need_number) - 1;
        }
      } else {
        option.need_number = Number(option.need_number) + 1;
      }
      this.$set(this.purchase, index, option)
      this.countPrice()
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    clearList() {
      this.purchase = [];
      this.goods_number = 0;
      this.count = 0;
    },
    deleteFn(index) {
      this.purchase.splice(index, 1)
      if (this.purchase.length) {
        this.countPrice()
      } else {
        this.goods_number = 0;
        this.count = 0;
      }
    },
    // 同步数据
    getInformation(option) {
      for (let item of option) {
        if (item.type === 'img' && item.number === 1) {
          this.infoForm.pic = item.value[0].url
        }
      }
    },
    downexcel() {
      if (!this.purchase.length) {
        this.$message.error('请添加需要申购的物品')
        return
      }
      let optionData = this.getJson(this.purchase);
      let that = this;
      let name_ = [];
      let word_price = []
      let word_number = []
      for (let index in optionData) {
        if (optionData[index].cate_son_id) {
          optionData[index].cate_id = optionData[index].cate_son_id;
        }
        delete optionData[index].cate_son_id

        if (name_.indexOf(optionData[index].name) !== -1) {
          this.$message.error('申购的物件名称不可重复')
          return
        } else {
          name_.push(optionData[index].name)
        }

        // 价格 数量格式 判断
        let price_ = Number(optionData[index].price)
        let nees_number = Number(optionData[index].need_number)
        if (isNaN(price_)) {
          console.log('price_:', price_)
          word_price.push(`【${Number(index) + 1}·${optionData[index].name}】`)
        }
        if (isNaN(nees_number)) {
          console.log('nees_number:', nees_number)
          word_number.push(`【${Number(index) + 1}·${optionData[index].name}】`)
        }
      }
      let string_ = ''
      if (word_price.length) {
        string_ = string_ + word_price.join('') + '，价格格式错误！'
      }
      if (word_number.length) {
        string_ = string_ + word_number.join('') + '，数量格式错误！'
      }
      if (string_) {
        this.$confirm(string_, '错误提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
        }).catch(() => {
        });
        return
      }
      console.log('错误提示:', optionData)
      // let listNew = []
      // for(let index in optionData){
      //   if(index<10){
      //     let item = optionData[index]
      //     delete item.url
      //     listNew.push(item)
      //   }
      // }
      // let sta = 1
      // if(sta){
      //   return
      // }
      purchaseExport({
        type: this.tabPosition === 'materiel' ? 1 : 2,
        list: JSON.stringify(optionData)
      }).then(res=>{
        // this.fileDownload(res, '申购当前清单.xlsx')
        console.log('获取的内容信息：', res)
        this.downExcelSrc = ''
        setTimeout(()=>{
          that.downExcelSrc = res.file
        },200)
      })
    },
    fileDownload(data, fileName) {
      let blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      let filename = fileName || 'filename.xls'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        let blobURL = window.URL.createObjectURL(blob)
        let tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', fileName)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    },
    // 识别采购文件,
    async handleBeforeUpload(file) {
      //选择文件后
      let _this = this
      console.log('file:', file)
      //检测文件类型
      if (!_this.checkFileType(file)) {
        console.log('抱歉，请选择excel文件')

        _this.showLoading(false)
        return false
      }

      //选择excel文件后，并读取其内容（文件流）
      let dataBinary = await this.analysis(file)
      console.log('识别的文件', dataBinary)
      // if (dataBinary != null) {
      //   this.testFn(dataBinary)
      // }
    },
    //解析excel
    analysis(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            console.log(sheetName)
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            });
          });
          resolve(result);
        };
        reader.readAsBinaryString(file);
        // reader.readAsBinaryString(file) // 传统input方法
      });
    },
    beforeAvatarUpload(file) {
      console.log('上传之前：', file)
      if (!this.checkFileType(file)) {
        this.$message.error('抱歉，请选择excel文件')
        return
      }
    },
    checkFileType(file) {
      let _this = this

      let flog = false

      //得到上传文件的值
      let fileName = file.name
      console.log('fileName:', fileName)
      //取其类型
      let fileType = fileName.lastIndexOf('.')

      //返回位于String对象中指定位置的子字符串并转换为小写.
      let extension = fileName
          .substring(fileType)
          .toLowerCase()
          .replace('.', '')
      //判断允许上传的文件格式
      if (_this.allowed.includes(extension)) {
        flog = true
      } else {
        flog = false
      }

      return flog
    },
  }
}
</script>

<style scoped>
.apply-box-left-from .el-form-item {
  margin-bottom: 10px;
}

.apply-box {
  display: flex;
}

.apply-box-left {
  flex: 1;
  margin-right: 20px;
}

.apply-box-right {
  width: 500px;
  border: 1px solid #999;
  border-radius: 5px;
  background: #ffe5c2;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.apply-box-right-top {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.apply-box-right-bottom {
  background: #fff;
  height: 80px;
  display: flex;
  flex-direction: column;
  padding: 0 10px;
  border-top: 1px solid #999;
}

.apply-box-right-bottom-l {
  height: 40px;
  text-align: right;
  line-height: 40px;
}

.apply-box-right-bottom-l span {
  font-size: 16px;
}

.apply-box-right-bottom-l span.price {
  color: #1b8de5;
  font-size: 20px;
  padding: 0 5px;
}

.apply-box-right-bottom-b {
  text-align: right;
}

.apply-box-right-list {
  margin-bottom: 10px;
  border-bottom: 1px dashed #333;
  padding-bottom: 15px;
  cursor: pointer;
}

.apply-box-right-list:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.apply-box-right-list-top {
  display: flex;
  margin-bottom: 5px;
}

.apply-box-right-list-top div {
  flex: 1;
}

.apply-box-right-list-top div span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 230px;
  display: block;
}

.apply-box-right-list-box {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 10px;
  position: relative;
}

.detele-box {
  position: absolute;
  right: -10px;
  top: -15px;
  font-size: 28px;
  color: red;
}

.detele-box:hover {
  text-decoration: underline;
}

.rightapply-box-right-list-box-img {
  display: flex;
  align-items: center;
  width: 230px;
}

.rightapply-box-right-list-box-img-in {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f4f4f4;
  margin-right: 10px;
}

.rightapply-box-right-list-box-img-in i {
  font-size: 40px;
  color: #aaa;
}

.rightapply-box-right-list-box-img-title {
  font-size: 16px;
}

.rightapply-box-right-list-box-img-title p:last-child {
  font-size: 14px;
  color: #999;
}

.rightapply-box-right-list-box-number {
  display: flex;
  align-items: center;
  width: 110px;
  margin: 0 10px;
}

.rightapply-box-right-list-box-number span {
  font-size: 22px;
  cursor: pointer;
}

.rightapply-box-right-list-box-number span:hover {
  text-decoration: underline;
}

.rightapply-box-right-list-box-price {
  font-size: 20px;
  flex: 1;
  text-align: center;
}

.rightapply-box-right-list-box-price span {
  font-size: 14px;
}

.rightapply-box-right-list-box-price:hover {
  text-decoration: underline;
}

.inline-input {
  width: 100%;
}

.apply-box-left-from {
  background: #f4f4f4;
  padding: 10px 20px;
}

.add-img .rightapply-box-right-list-box-img-in {
  border: 1px solid #ddd;
  background: #fff;
}

.apply-nonedata {
  text-align: center;
  color: #999;
  font-size: 20px;
  padding: 150px 0;
}

.upload-demo-line {
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-upload__tip {
  text-align: center;
}
</style>
